//
//  ExScreenRecorderViewController.m
//  OC-Example
//
//  Created by lcj on 2020/11/3.
//  Copyright © 2020 apang.men. All rights reserved.
//

#import "ExScreenRecorderViewController.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import "ExScreenRecorderManager.h"
#endif
#import <AVKit/AVKit.h>
@interface ExScreenRecorderViewController ()
@property (nonatomic, strong) UIButton * recordButton;
@end

@implementation ExScreenRecorderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (@available(iOS 13.0, *)) {
        [self.view setBackgroundColor:[UIColor systemBackgroundColor]];
    } else {
        // Fallback on earlier versions
        [self.view setBackgroundColor:[UIColor whiteColor]];
    }
    self.title = @"屏幕录制";
    _recordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _recordButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_recordButton setTitle:@"开始录制" forState:UIControlStateNormal];
    [_recordButton setTitle:@"停止录制" forState:UIControlStateSelected];
    [self.view addSubview:_recordButton];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_recordButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_recordButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    [_recordButton addTarget:self action:@selector(recordAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [button setTitle:@"预览" forState:UIControlStateNormal];
    [self.view addSubview:button];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_recordButton attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20]];
    [button addTarget:self action:@selector(preview) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.translatesAutoresizingMaskIntoConstraints = NO;
    [button1 setTitle:@"删除" forState:UIControlStateNormal];
    [self.view addSubview:button1];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:button attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20]];
    [button1 addTarget:self action:@selector(deleteFile) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (@available(iOS 9.0, *)) {
        self.recordButton.selected = [ExScreenRecorderManager isRecording];
    }
}

- (void)recordAction {
    if (_recordButton.selected == NO) {
        _recordButton.selected = YES;
        [self startRecord];
    } else {
        _recordButton.selected = YES;
        [self stopRecord];
    }
}

- (void)startRecord {
    __weak typeof(self) weakSelf = self;
    if (@available(iOS 9.0, *)) {
        ExScreenRecorderConfiguration * configuration = [[ExScreenRecorderConfiguration alloc] init];
        if (@available(iOS 11.0, *)) {
            configuration.fileName = [NSString stringWithFormat:@"%d",arc4random_uniform(100000)+100000];
        }
        [ExScreenRecorderManager startRecordingWithConfiguration:configuration handler:^(NSError * _Nullable error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.recordButton.selected = YES;
                });
            }
        }];
    }
}

- (void)stopRecord {
    __weak typeof(self) weakSelf = self;
    if (@available(iOS 9.0, *)) {
        [ExScreenRecorderManager stopRecordingWithHandler:^(RPPreviewViewController * _Nullable previewViewController, NSString * _Nullable filePath, NSError * _Nullable error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.recordButton.selected = NO;
                    if (previewViewController != nil) {
                        [weakSelf presentViewController:previewViewController animated:YES completion:nil];
                    }
                });
            }
        }];
    }
}

- (void)preview {
    NSString * folder = [[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.men.apang.Example"] URLByAppendingPathComponent:@"videos"].relativePath;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray * files = [fileManager contentsOfDirectoryAtPath:folder error:nil];
    if (files.count == 0) {
        folder = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"videos"];
        files = [fileManager contentsOfDirectoryAtPath:folder error:nil];
    }
    if (files.count > 0) {
        UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"选择视频" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        for (NSString * _file in files) {
            NSString * filePath = [folder stringByAppendingPathComponent:_file];
            NSLog(@"%@  %d",filePath,[fileManager fileExistsAtPath:filePath]);
            if ([fileManager fileExistsAtPath:filePath]) {
                __weak typeof(self) weakSelf = self;
                UIAlertAction * action = [UIAlertAction actionWithTitle:_file style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [weakSelf playerVideo:filePath];
                }];
                [alertVC addAction:action];
            }
        }
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancel];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)playerVideo:(NSString *)filePath {
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];
    playerVC.player = [AVPlayer playerWithURL:[NSURL fileURLWithPath:filePath]];
    [self presentViewController:playerVC animated:YES completion:nil];
}

- (void)deleteFile {
    NSString * folder = [[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.men.apang.Example"] URLByAppendingPathComponent:@"videos"].relativePath;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray * files = [fileManager contentsOfDirectoryAtPath:folder error:nil];
    if (files.count == 0) {
        folder = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"videos"];
        files = [fileManager contentsOfDirectoryAtPath:folder error:nil];
    }
    if (files.count > 0) {
        NSString * filePath = [folder stringByAppendingPathComponent:files.firstObject];
        NSError * error;
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        NSLog(@"delete file:%@",error);
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
